package by2019;
/*
 * LeetCode 122
 * 给定一个数组，它的第i个元素是一支给定股票第i天的价格
 * 你可以多次买卖一支股票
 * 不能同时参与多笔交易，即不能买入多次
 * 计算能获得的最大利润
 */
public class 买卖股票的最佳时机 {
	public static void main(String[] args) {
		int[] prices = new int[] {1,2,3,4,5} ;
		int mony = maxProfitX(prices);
		System.out.println(mony);
	}
	
	//自己思路写的，有点像贪心算法
	 public static int maxProfit(int[] prices) {
		 boolean gupiao = false ;
		 int in = 0 ;
		 int mony = 0 ;
		 int length = prices.length ;
		 
		 if(prices.length==0)
			 return 0 ;
		 
		 if(prices[prices.length-1]<prices[prices.length-2]) 
			 length -- ;
		
		 try {
		 for(int i=0;i<length;i++) {
			 if(prices[i+1]>prices[i]) {
				 if(!gupiao) {
					 in = i ;
					 System.out.println("买入: "+prices[i]);
					 gupiao = true ;
				 }
			 } else {
				 if(gupiao) {
					 mony = prices[i] - prices[in] + mony ;
					 in = 0 ;
					 gupiao = false ;
					 System.out.println("卖出: "+prices[i]);
				 }
			 }
			 if(i==prices.length-1) {
				 System.out.println("明天就没得买啦");
				 mony = prices[i] - prices[in] + mony ;
				 break ;
			 }
			 
		 }
		 }catch (ArrayIndexOutOfBoundsException e) {
			 mony = prices[prices.length-1] - prices[in] + mony ;
			 System.out.println("捕捉异常成功，mony="+mony);
			 return mony ;
			 
		}
		 return mony ;
	 }
	 
	 //贪心算法
	 //只要明天的股价比今天高，我就在今天买入，明天卖出
	 public static int maxProfitX(int[] prices) {
		 
		 int mony = 0 ;
		 
		 for(int i=1;i<prices.length;i++) {
			 if(prices[i]>prices[i-1]) {
				 mony = mony + prices[i] - prices[i-1] ;
			 }
		 }
		 return mony ;
	 }
}
